<template>
  <a-modal
    :title="$t('导入库存')"
    :width="700"
    :visible="visible"
    :confirmLoading="uploading"
    @cancel="handleClose"
    @ok="handleImport"
  >
    <a-spin :spinning="uploading" style="padding: 0 20px">
      <div style="margin-bottom:20px;">
        <span style="opacity:0;">*</span><span style="color:#666;">{{$t('导入模板')}}：</span>
        <a-button type="primary" icon="download" @click="handleExportXls($t('采购单导入模板'))">{{$t('下载模板')}}</a-button>
      </div>
      <div style="margin-bottom:20px;">
        <span style="color:#F00;">*</span><span style="color:#666;">{{$t('选择仓库')}}：</span>
        <j-tree-select
          :placeholder="$t('请选择')"
          v-model="store"
          dict="bis_goods_store,name,id"
          pid-field="pid"
          pidValue="0"
          hasChildField="has_child"
          style="width:400px;margin-right:6px;vertical-align: middle;"
        ></j-tree-select>
      </div>
      <div style="margin-bottom:20px;">
        <span style="opacity:0;">*</span><span style="color:#666;">{{$t('订单备注')}}：</span>
        <a-textarea style="width:400px;margin-right:6px;vertical-align: top;" v-model="comment"></a-textarea>
      </div>
      <div style="margin-bottom:20px;">
        <span style="color:#F00;">*</span><span style="color:#666;">{{$t('导入文件')}}：</span>
        <a-input style="width:400px;margin-right:6px;vertical-align: bottom;" :placeholder="$t('请选择要导入的文件')" disabled v-model="name"></a-input>
        <a-upload
          name="file"
          :showUploadList="false"
          :action="importExcelUrl"
          :multiple="false"
          :headers="tokenHeader"
          @change="handleImportExcel1"
        >
          <a-button style="background-color: #f59a23; color: #ffffff">{{ $t('选择') }}</a-button>
        </a-upload>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from "@/store/mutation-types"
import { postAction } from '@/api/manage'
export default {
  name: 'ImportModal',
  data() {
    return {
      visible: false,
      uploading: false,
      filename:'',
      store:"",
      name:'',
      url:{
        importExcelUrl: 'sys/common/upload',
      },
      inType:1,
      comment:''
    }
  },
  computed: {
    tokenHeader(){
      let head = {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)}
      let tenantid = Vue.ls.get(TENANT_ID)
      if(tenantid){
        head['tenant-id'] = tenantid
      }
      return head;
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  mounted() {},
  methods: {
    handleImportExcel1(info) {
      if (info.file.status !== 'uploading') {
        this.name = info.file.name
        this.filename = info.file.response.message
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          if (info.file.response.code === 201) {
            let {
              message,
              result: { msg, fileUrl, fileName },
            } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            // this.$warning({
            //   title: message,
            //   content: (
            //     <div>
            //       <span>{msg}</span><br/>
            //       <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
            //     </div>
            //   )
            // })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name}` + this.$t('文件上传成功'))
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(this.$t('文件上传失败') + ': ' `${info.file.msg} `)
      }
    },
    handleExportXls(fileName){
      if(!fileName || typeof fileName != "string"){
        fileName = "导出文件"
      }
      let url=window._CONFIG['domianURL'] + 'importTemplate/采购单导入模板.xls'
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放掉blob对象
      return
    },
    handleClose() {
      this.visible = false
    },
    show() {
      this.filename=''
      this.name=''
      this.comment=''
      this.store=''
      this.uploading = false
      this.visible = true
    },
    handleImport() {
      let that=this
      if(!that.store){
        that.$message.warning(that.$t('请选择仓库'))
        return
      }
      if(!that.filename){
        that.$message.warning(that.$t('请选择要导入的文件'))
        return
      }
      let query={
        inType:that.inType,
        store:that.store,
        comment:that.comment,
        filename:that.filename
      }
      that.uploading = true
      postAction('/goods/bisGoodsInstock/importExcel', query).then(res => {
        if (res.success) {
          if (res.code == 201) {
            that.errorTip(res.message, res.result)
          } else {
            that.$message.success(res.message)
          }
          that.visible = false
          that.$emit('ok')
        } else {
          that.$message.warning(res.message)
        }
      }).finally(()=>{
        that.uploading = false
      })
    },
    // 错误信息提示
    errorTip(tipMessage, fileUrl) {
      let that=this
      const h = that.$createElement
      let href = window._CONFIG['domianURL'] + fileUrl
      that.$warning({
        title: that.$t('导入成功,但是有错误数据'),
        content: h('div', {}, [
          h('div', tipMessage),
          h('span', that.$t('具体详情请 ')),
          h(
            'a',
            {
              attrs: {
                href: href,
                target: '_blank'
              }
            },
            that.$t('点击下载')
          )
        ]),
        onOk() {}
      })
    }
  }
}
</script>

<style scoped>
</style>